package com.heavenick.core.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.heavenick.app.model.pojo.Simple;

/**
 * Map处理的工具类
 * @author Flouny.Caesar
 *
 */
public class MapUtil {
	
	/**
	 * 将一个Bean转换成Map
	 * @param data
	 * @return
	 */
	public static Map<Object, Object> populateMap(Object data) {
		
		return populateMap(new HashMap<Object, Object>(), data);
	}
	
	/**
	 * 将一个Bean转换成Map
	 * @param map
	 * @param data
	 * @return
	 */
	public static Map<Object, Object> populateMap(Map<Object, Object> populateMap, Object data) {
		if (populateMap == null) throw new RuntimeException("populateMap and data is not empty!");
		if (data == null) return populateMap;
		if(data instanceof Map){
			populateMap.putAll((Map)data);
			return populateMap;
		}		
		for (Field field : data.getClass().getDeclaredFields()) {
			try {
				String fieldMethod = "get" + field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1);
				Method method = data.getClass().getMethod(fieldMethod,null);
				populateMap.put(field.getName(), method.invoke(data, null));
			} catch (NoSuchMethodException e) {
				try {
					Method method = data.getClass().getMethod(field.getName(),null);
					populateMap.put(field.getName(), method.invoke(data, null));
				} catch (Exception e1) {
				} 
			} catch (Exception e) {
			}
		}
		return populateMap;
	}
}